/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.leaveMsg.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.activity.domain.Activity;
import com.fzhucc.modules.activity.domain.dto.ActivityQueryCriteria;
import com.fzhucc.modules.fenRecordLog.service.FenRecordLogService;
import com.fzhucc.modules.leaveMsg.domain.LeaveMsg;
import com.fzhucc.modules.leaveMsg.domain.dto.LeaveMsgAddDto;
import com.fzhucc.modules.leaveMsg.domain.dto.LeaveMsgEditDto;
import com.fzhucc.modules.sciCxResult.domain.dto.SciCxResultQueryCriteria;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.service.mapstruct.UserMapper;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.leaveMsg.repository.LeaveMsgRepository;
import com.fzhucc.modules.leaveMsg.domain.dto.LeaveMsgDto;
import com.fzhucc.modules.leaveMsg.domain.dto.LeaveMsgQueryCriteria;
import com.fzhucc.modules.leaveMsg.service.mapstruct.LeaveMsgMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-01-11
 **/
@Service
@RequiredArgsConstructor
public class LeaveMsgService {

    private final LeaveMsgRepository leaveMsgRepository;

    private final FenRecordLogService fenRecordLogService;

    private final UserRepository userRepository;
    private final LeaveMsgMapper leaveMsgMapper;

    private final UserMapper userMapper;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    @Value("${fen.type.gw}")
    public String gw;

    //根据不同设置不同的部门查看 处理  福建省;  或者  福建省;福州市;   或者 福建省;福州市;马尾区; 这种类型
    public String setCriteria(LeaveMsgQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            } else {
                return orgArea;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//包含福建省 则查全部
                return null;
            } else {
                if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return null;
                }
                if (res.getOrgArea().contains(";")) {
                    String[] split = res.getOrgArea().split(";");
                    if (split.length == 2) {
                        return split[1];
                    } else if (split.length == 3) {
                        return split[2];
                    } else if (split.length == 1) {
                        return split[0];
                    } else {
                        throw new BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            }
        } else {
            throw new BadRequestException("用户ID未找到");
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                //不赋予则返回所有都能看
                return null;
            }
            if (res.getOrgArea().contains(";")) {
                String[] split = res.getOrgArea().split(";");
                if (split.length == 2) {
                    return split[1];
                } else if (split.length == 3) {
                    return split[1];
                } else if (split.length == 1) {
                    return split[0];
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            } else {
                throw new BadRequestException("未符合规范的地区区域");
            }
        }
    }

    public Map<String, Object> my(LeaveMsgQueryCriteria criteria, Pageable pageable) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("未找到登录用户");
        }
        criteria.setUserId(userId);
        Page<LeaveMsg> page = leaveMsgRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<LeaveMsgDto> map = page.map(leaveMsgMapper::toDto);
        List<LeaveMsgDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (LeaveMsgDto dto : list) {
                if (dto.getUserId() != null) {
                    Optional<User> ops = userRepository.findById(dto.getUserId());
                    if (ops.isPresent()) {
                        dto.setUserDto(userMapper.toDto(ops.get()));
                    }
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public Map<String, Object> queryAll(LeaveMsgQueryCriteria criteria, Pageable pageable) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(gw);
        } catch (Exception e) {

        }

        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        Page<LeaveMsg> page = leaveMsgRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<LeaveMsgDto> map = page.map(leaveMsgMapper::toDto);
        List<LeaveMsgDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (LeaveMsgDto dto : list) {
                if (dto.getUserId() != null) {
                    Optional<User> ops = userRepository.findById(dto.getUserId());
                    if (ops.isPresent()) {
                        dto.setUserDto(userMapper.toDto(ops.get()));
                    }
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public List<LeaveMsgDto> queryAll(LeaveMsgQueryCriteria criteria) {
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        return leaveMsgMapper.toDto(leaveMsgRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Transactional
    public LeaveMsgDto findById(Integer id) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(gw);
        } catch (Exception e) {

        }

        LeaveMsg leaveMsg = leaveMsgRepository.findById(id).orElseGet(LeaveMsg::new);
        ValidationUtil.isNull(leaveMsg.getId(), "LeaveMsg", "id", id);
        return leaveMsgMapper.toDto(leaveMsg);
    }

    @Transactional(rollbackFor = Exception.class)
    public LeaveMsgDto create(LeaveMsgAddDto dto) {
        LeaveMsg resources = new LeaveMsg();
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {

        }
        if (dto.getSort() != null) {
            resources.setSort(dto.getSort());
        } else {
            resources.setSort(1);
        }
        if (dto.getIsShow() != null) {
            resources.setIsShow(dto.getIsShow());
        } else {
            resources.setIsShow(0);
        }
        resources.setName(dto.getName());
        resources.setUnit(dto.getUnit());
        resources.setContext(dto.getContext());
        resources.setWay(dto.getWay());
        resources.setUserId(userId);
        //调整为登录账号为哪个市的添加哪个市
        if (dto.getOrgArea() != null && !dto.getOrgArea().equals("")) {
            resources.setOrgArea(dto.getOrgArea());
        } else {
            resources.setOrgArea(orgAreaReturn());
        }
        return leaveMsgMapper.toDto(leaveMsgRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(LeaveMsgEditDto dto) {
        LeaveMsg leaveMsg = leaveMsgRepository.findById(dto.getId()).orElseGet(LeaveMsg::new);
        ValidationUtil.isNull(leaveMsg.getId(), "LeaveMsg", "id", dto.getId());

        if (dto.getSort() != null) {
            leaveMsg.setSort(dto.getSort());
        }
        if (dto.getIsShow() != null) {
            leaveMsg.setIsShow(dto.getIsShow());
        }
        leaveMsg.setName(dto.getName());
        leaveMsg.setUnit(dto.getUnit());
        leaveMsg.setContext(dto.getContext());
        leaveMsg.setWay(dto.getWay());

        //传进来是什么就什么 没有则用登录
        if (dto.getOrgArea() != null && !dto.getOrgArea().equals("")) {
            leaveMsg.setOrgArea(dto.getOrgArea());
        } else {
            leaveMsg.setOrgArea(orgAreaReturn());
        }
        leaveMsgRepository.save(leaveMsg);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            leaveMsgRepository.deleteById(id);
        }
    }

    public void download(List<LeaveMsgDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (LeaveMsgDto leaveMsg : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("昵称", leaveMsg.getName());
            map.put("单位", leaveMsg.getUnit());
            map.put("联系方式", leaveMsg.getWay());
            map.put("内容", leaveMsg.getContext());
            map.put("用户id", leaveMsg.getUserId());
            map.put("是否显示默认显示", leaveMsg.getIsShow());
            map.put("排序", leaveMsg.getSort());
            String orgArea = leaveMsg.getOrgArea();
            if (orgArea != null) {
                if (orgArea.contains(";")) {
                    String[] split = orgArea.split(";");
                    String str = "";
                    for (String a : split) {
                        str = str + a + "/";
                    }
                    map.put("所属工会", str);
                } else {
                    map.put("所属工会", orgArea);
                }
            } else {
                map.put("所属工会", "");
            }
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}